﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace Aceso.Server.DAL
{
    public class DbContextFactory<TContext> : IDbContextFactory<TContext>, IDisposable where TContext : DbContext, new()
    {
        private string _connectionString;
        private TContext _context;

        public DbContextFactory()
        {
            //_connectionString = ConfigurationManager.ConnectionStrings["DefaultModelConnectionString"].ConnectionString;
            //_context.Database.Connection.ConnectionString = _connectionString;

            //在TContext的构造函数中自动获取ConnectionString
            _context = Activator.CreateInstance<TContext>();
        }

        public DbContextFactory(string connectionString) : this()
        {
            _connectionString = connectionString;
        }

        public TContext GetDbContext()
        {
            return _context == null ? Activator.CreateInstance<TContext>() : _context;

            //获取当前EF上下文的唯一实例
            //TContext obj = CallContext.GetData(typeof(TContext).FullName) as TContext;
            //if (obj == null)
            //{
            //    obj = new TContext();
            //    CallContext.SetData(typeof(TContext).FullName, obj);
            //}
            //return obj;
        }

        private bool disposed = false;
        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    if (_context != null)
                        _context.Dispose();
                }
            }
            this.disposed = true;
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}
